package com.dsdl.chatapp.common.utils.connect;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.CallSuper;
import android.support.annotation.UiThread;

import com.dsdl.chatapp.common.utils.AESUtil;
import com.dsdl.chatapp.common.utils.SPUtil;
import com.dsdl.chatapp.common.utils.StringUtils;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * Created by zzg on 2016/7/30.
 */
public class HttpManager {
    private static String TAG = "HttpManager";
    private static String HTTP_IP = "http://192.168.0.123:3100";
    private static int TIME_OUT = 5 * 1000;
    private HttpManager INSTANCE;

    private CommonCallBack mCommonCallBack;

    private UIHandler mUIUiHandler;

    private HttpManager() {
        if (INSTANCE == null) {
            INSTANCE = this;
        }
    }

    public static HttpManager getInstance() {
        return new HttpManager();
    }

    public UIHandler getUIHandler() {
        if (mUIUiHandler == null) {
            mUIUiHandler = new UIHandler();
        }
        return mUIUiHandler;
    }

    public void get(String url, List<RequestParam> params, CommonCallBack callBack) {
        String URL = HTTP_IP + url;
        this.mCommonCallBack = callBack;
        new ConnectThread(URL, HttpMethod.GET.toString(), null, params, null).start();
    }

    public void post(String url, List<HttpHeader> headers, String param, CommonCallBack callBack) {
        String URL = HTTP_IP + url;
        this.mCommonCallBack = callBack;
        new ConnectThread(URL, HttpMethod.POST.toString(), headers, null, param).start();
    }

    public void post(String url, List<HttpHeader> headers, CommonCallBack callBack) {
        String URL = HTTP_IP + url;
        this.mCommonCallBack = callBack;
        new ConnectThread(URL, HttpMethod.POST.toString(), headers, null, null).start();
    }

    class ConnectThread extends Thread {
        private String url = null;
        private String method;
        private String param;
        private List<HttpHeader> httpHeaders;
        private List<RequestParam> params;

        public ConnectThread(String url, String method, List<HttpHeader> headers, List<RequestParam> params, String param) {
            this.url = url;
            this.method = method;
            this.params = params;
            this.param = param;
            this.httpHeaders = headers;
        }

        @Override
        public void run() {
            super.run();
            try {
                if ("GET".equals(method)) {
                    StringBuffer url_params = new StringBuffer();
                    for (RequestParam requestParam : params) {
                        url_params.append("&");
                        url_params.append(requestParam.getName());
                        url_params.append("=");
                        url_params.append(requestParam.getValue());
                    }
                    if (url_params.length() > 0) {
                        url_params.deleteCharAt(0);
                    }
                    url = url + "?" + url_params.toString();
                }
                URL url = new URL(this.url);
                URLConnection rulConnection = url.openConnection();
                HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;
                // 设置连接超时时间
                httpUrlConnection.setConnectTimeout(TIME_OUT);
                httpUrlConnection.setRequestMethod(method);
                httpUrlConnection.setRequestProperty("Accept-Encoding", "identity");
                if ("POST".equals(method)) {
                    httpUrlConnection.setRequestProperty("Content-type", "application/raw");
                    // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
                    // http正文内，因此需要设为true, 默认情况下是false;
                    httpUrlConnection.setDoOutput(true);
                    // 设置是否从httpUrlConnection读入，默认情况下是true;
                    httpUrlConnection.setDoInput(true);
                    // Post 请求不能使用缓存
                    httpUrlConnection.setUseCaches(false);
                    if (this.param != null) {
                        // 发送请求参数
                        DataOutputStream dos = new DataOutputStream(httpUrlConnection.getOutputStream());
                        // 请求的参数转换为byte数组
                        byte[] postData = param.getBytes();
                        dos.write(postData);
                        dos.flush();
                        dos.close();
                    }
                }
                if (httpHeaders != null) {
                    for (HttpHeader httpHeader : httpHeaders) {
                        httpUrlConnection.setRequestProperty(httpHeader.getName(), httpHeader.getValue());
                    }
                }
                // 连接，从上述第2条中url.openConnection()至此的配置必须要在connect之前完成，
                httpUrlConnection.connect();
                int resCode = httpUrlConnection.getResponseCode();
                if (resCode == HttpURLConnection.HTTP_OK) {
                    int length = httpUrlConnection.getContentLength();
                    // 处理数据, 取得响应内容
                    InputStream in = httpUrlConnection.getInputStream();
                    try {
                        byte[] bytes = StringUtils.input2byte(in);
                        String string = new String(bytes);
                        Message message = Message.obtain();
                        message.what = 1;
                        message.obj = string;
                        getUIHandler().sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    Message message = Message.obtain();
                    message.what = 3;
                    message.obj = resCode;
                    getUIHandler().sendMessage(message);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @UiThread
    @CallSuper
    private void getResponseData(int resCode, String response) {
        if (resCode == 200) {
            mCommonCallBack.success(response);
        } else {
            mCommonCallBack.fails(resCode, response);
        }

    }

    public interface CommonCallBack {
        void success(String response);

        void fails(int status, String errorMessage);
    }

    class UIHandler extends Handler {
        public UIHandler() {
            super(Looper.getMainLooper());
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    getResponseData(200, (String) msg.obj);
                    break;
                case 2:
                    getResponseData(0, "ContentLength小于1");
                    break;
                case 3:
                    getResponseData((int) msg.obj, "请求错误");
                    break;
                default:
                    break;
            }
        }
    }

}
